package com.numberma.userservice.Intercepter;

import com.numberma.userservice.Utils.JwtUtil;
import com.numberma.userservice.Utils.ThroadLocal;
import com.numberma.userservice.constant.JwtConstant;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class UserIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(JwtConstant.JWT_HEADER);

        try {
            log.info("jwt校验:{}", token);

            Claims claims = JwtUtil.ParseJwt(token, JwtConstant.JWT_SECRET);

            log.info("当前登录用户id为:{},身份为:{}",claims.get("userId"),claims.get("roleCode"));
            ThroadLocal.set(claims);

            return true;
        } catch (Exception ex) {
            //不通过，响应401状态码
            response.setStatus(401);
            log.info("jwt校验失败,{}",token);
            return false;
        }
    }

}
